Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
Array of Objects -> filter keys or values by startsWith -> merge result to object

I have an array of objects:

let cars = [
  {
    "color_1": "purple",
    "color_2": "red",
    "type": "minivan",
    "capacity": 7,
    "all_colors": []
  },
  {
    "color_1": "blue",
    "color_2": "orange",
    "type": "station wagon",
    "capacity": 5,
    "all_colors": []
  }
]

I want to filter all keys (startsWith) "color..." and merge them into "all_colors" like this:

let cars = [
  {
    "color_1": "purple",
    "color_2": "red",
    "type": "minivan",
    "capacity": 7,
    "all_colors": ['purple', 'red']
  },
  {...}
]

I tried this:

var res = Object.keys(Object.assign({}, ...cars)).filter(v => v.startsWith('color'));
console.log(res)

but i need it for all objects and i don't know how to add the results into "all_colors"?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can do it like this:

let cars = [
  { "color_1": "purple", "color_2": "red", "type": "minivan" ,"capacity": 7, "all_colors": [] },
  { "color_1": "blue", "color_2": "orange", "type": "station wagon","capacity": 5, "all_colors": [] }
];

for (const car of cars) {
  const color_properties = Object.keys(car).filter((key) => key.startsWith('color'));
  car.all_colors = color_properties.map((color) => car[color]);
}

console.log(cars);

about 4 years ago · Juan Pablo Isaza Report

0

You could get entries, filter and map the values.

const
    cars = [{ color_1: "purple", color_2: "red", type: "minivan", capacity: 7, all_colors: [] }, { color_1: "blue", color_2: "orange", type: "station wagon", capacity: 5, all_colors: [] }],
    result = cars.map(o => ({ ...o, all_colors: Object
         .entries(o)
         .filter(([k]) => k.startsWith('color'))
         .map(([, v]) => v)
    }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!